package com.ky.facescan;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.alipay.iot.bpaas.api.BPaaSApi;
import com.alipay.iot.bpaas.api.BPaaSInitCallback;
import com.alipay.iot.bpaas.api.service.BPaaSCallback;
import com.alipay.iot.bpaas.api.service.BPaaSResponse;
import com.alipay.iot.bpaas.api.service.LocalService;
import com.google.gson.Gson;
import com.ky.facescan.base.SmileManager;
import com.ky.facescan.base.mvp.MVPBaseActivity;
import com.ky.facescan.bean.MyEvent;
import com.ky.facescan.databinding.ActivityMainBinding;
import com.ky.facescan.device.telpo.CodeScan;
import com.ky.facescan.device.telpo.IDCardScan;
import com.ky.facescan.utils.DeviceUtils;
import com.ky.facescan.utils.LogUtils;
import com.ky.facescan.utils.ToastUtils;
import com.telpo.tps550.api.idcard.IdentityMsg;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;


public class MainActivity extends MVPBaseActivity<ActivityMainBinding, MainContract.View, MainPresenter> implements MainContract.View, IDCardScan.IDCardScanCallback, CodeScan.CodeScanCallback {
    private Handler mHandler;
    private final Runnable mRedoDetectTask = () -> SmileManager.getInstance().detect();

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarDarkFont(false);
        this.mHandler = new Handler(Looper.myLooper());
        IDCardScan.getInstance(this).setIdCardScanCallback(this);
        CodeScan.getInstance(this).setCodeScanCallback(this);
        initAlipayBPaaSApi();
        mBinding.tvAppVersion.setText("版本:v" + DeviceUtils.getVersionName(this));
        mBinding.tvDeviceSN.setText("SN:" + DeviceUtils.getDeviceSN());

    }

    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        this.mHandler.post(this.mRedoDetectTask);
        this.mHandler.postDelayed(this.mRedoDetectTask, 10000L);
    }

    protected void onPause() {
        super.onPause();
        EventBus.getDefault().removeAllStickyEvents();
        EventBus.getDefault().unregister(this);
        this.mHandler.removeCallbacks(this.mRedoDetectTask, (Object) null);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventReceive(MyEvent event) {
        switch (event.mTag) {
            case "event_smile_install_start":
                break;
            case "event_smile_install_finish":
                if ((Boolean) event.mData) {
                    this.mHandler.postDelayed(this.mRedoDetectTask, 500L);
                } else {
                    this.mHandler.post(() -> ToastUtils.show("初始化失败"));
                }
                break;
            case "event_smile_detect":
                //前往支付宝组件
                ToastUtils.show("有人脸");
                toAlipayFaceScan();
        }

    }

    void initAlipayBPaaSApi() {
        Bundle extInfo = new Bundle();
//        extInfo.putLong(BPaaSApi.KEY_EXT_TIME_OUT, 2 * 60 * 600);
        BPaaSApi.getInstance().init(this, IsvConfig.APP_ID, IsvConfig.APP_VERSION, extInfo,
                new BPaaSInitCallback() {
                    @Override
                    public void onSuccess() {
                        LogUtils.d("BPaaSInitCallback", "onSuccess");
                    }

                    @Override
                    public void onFail(String errorMessage) {
                        LogUtils.d("BPaaSInitCallback", "onFail errorMessage=" + errorMessage);
                    }
                });
    }

    private void toAlipayFaceScan() {
        Bundle bundle = new Bundle();
        bundle.putString("serviceId", "faceAuth");
        bundle.putString("query", "QUERY");
        bundle.putString("scopes", "auth_user");
        BPaaSApi.getInstance().startBPaaSService(IsvConfig.APP_ID, "BPaaSSmileFaceAuth", bundle, new BPaaSCallback() {
            @Override
            public void onResponse(BPaaSResponse response) {
                if (response != null && response.getCode() == BPaaSResponse.RESULT_CODE_SUCCESS && response.getResult() != null) {
                    Bundle result = response.getResult().getBundle(LocalService.KEY_LOCAL_RESULT);
                    if (result != null) {
                        int code = result.getInt("code");
                        String extInfo = result.getString("extInfo");
                        String ftoken = result.getString("ftoken");
                        if (code == 1000 && !TextUtils.isEmpty(extInfo)) {
                            try {
                                JSONObject obj = new JSONObject(extInfo);
                                String authCode = obj.getString("authCode");
                                LogUtils.i("startBPaaSService", "authCode=" + authCode);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }

            @Override
            public void onEvent(String s, String s1, Bundle bundle) {
            }
        });
    }

    @Override
    public void codeResult(String code) {
        //二维码结果
        LogUtils.d("codeResult", code);
    }

    @Override
    public void idCardResult(IdentityMsg identityInfo) {
        //身份证结果
        LogUtils.d("idCardResult", new Gson().toJson(identityInfo));
    }
}